<template>
    <el-tree-select v-model="props.modelValue" :data="categoryData" check-strictly=true :render-after-expand="false"
                    :default-expand-all="true" @change="change"/>
</template>

<script lang="ts" setup>
import {ref, onMounted} from "vue";
import {categoryApi} from '@/api'

const props = defineProps({modelValue: {type: Number, default: 0}})
const emit = defineEmits(["update:modelValue"])


const categoryData = ref([])

onMounted(() => {
    callCategoryTreeApi()
})
const change = (value: number) => {
    emit('update:modelValue', value)
}
const callCategoryTreeApi = () => {
    categoryApi.select.call({}).then((res: any) => {
        res.forEach((item: any) => {
            //增加label与value属性与el-tree-select绑定遍历数据
            item.value = item.id
            item.label = item.name
        });
        // console.log(res)

        let categoryData1 = res;
        //reduce使扁平化数据树化
        let categoryData2 = categoryData1.reduce((duzi: any, currentValue: any) => {
            currentValue.children = categoryData1.filter((item: any) => item.parentId === currentValue.id)
            if (currentValue.parentId === 0) {
                duzi.push(currentValue)
            }
            return duzi;
        }, [])

        categoryData2 = [{
            value: 0,
            label: '一级目录',
        }].concat(categoryData2)
        categoryData.value = categoryData2

    })
}
defineExpose({callCategoryTreeApi})
</script>